#!/bin/sh

set -o errexit -o nounset -o pipefail

if [ -n "${XTRACE:-}" ]; then
    set -o xtrace
fi

VERSION="${1}"
CACHE_DIR="${CACHE_DIR:-${2}}"

# Update symlinks for k3s and images to new version
K3S_DIR="${CACHE_DIR}/${VERSION}"
if [ ! -d "${K3S_DIR}" ]; then
    echo "Directory ${K3S_DIR} does not exist"
    exit 1
fi

# Make sure any outdated kubeconfig file is gone
mkdir -p /etc/rancher/k3s
rm -f /etc/rancher/k3s/k3s.yaml

K3S=k3s
ARCH=amd64
if [ "$(uname -m)" = "aarch64" ]; then
    K3S=k3s-arm64
    ARCH=arm64
fi

# Add images
IMAGES="/var/lib/rancher/k3s/agent/images"
mkdir -p "${IMAGES}"
IMAGEPATH="${K3S_DIR}/k3s-airgap-images-${ARCH}"
if [ -f "${IMAGEPATH}.tar.zst" ]; then
    ln -s -f "${IMAGEPATH}.tar.zst" "${IMAGES}"
fi
if [ -f "${IMAGEPATH}.tar" ]; then
    ln -s -f "${IMAGEPATH}.tar" "${IMAGES}"
fi
# Add k3s binary
ln -s -f "${K3S_DIR}/${K3S}" /usr/local/bin/k3s
# The file system may be readonly (on macOS)
chmod a+x "${K3S_DIR}/${K3S}" || true

# Make sure any old manifests are removed before configuring k3s again.
# All Rancher Desktop manifest have a name like z123-foo-bar, so only delete
# those. That way provisioning scripts can still create other manifests.
# We need to create the directory before we run `k3s server ...` because
# we install additional manifests that k3s will install during startup.
MANIFESTS=/var/lib/rancher/k3s/server/manifests
rm -rf "${MANIFESTS}/z"[0-9]*
mkdir -p "$MANIFESTS"

STATIC=/var/lib/rancher/k3s/server/static/rancher-desktop
rm -rf "$STATIC"
mkdir -p "$STATIC"
